<?php
/**
 * 定时任务
 * Create by PhpStorm
 * User: lijia
 * Data: 2020/8/10
 * Time: 14:50
 */

namespace app\api\controller;

use app\api\business\CashBus;
use think\facade\Db;
use think\Request;

class Timer extends Common
{

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 删除超过一天时间未支付的订单
     */
    public function delUnpaid()
    {
        $date = date("Y-m-d H:i:s", strtotime("-1 day"));
        Db::name('recharge')->where('create_time', '<', $date)->where('status', 0)->delete();
        $orders = Db::name('orders')->where('create_time', '<', $date)->where('status', 1)->select()->toArray();
        if (!$orders) {
            return true;
        }
        Db::startTrans();
        try {
            foreach ($orders as $k => $v) {
                $goods = Db::name('orders_goods')->alias('a')
                    ->join('goods b', 'b.id =  a.goods_id')
                    ->where('a.orders_id', $v['id'])
                    ->field('a.goods_id,a.num,b.stock')
                    ->select()->toArray();
                foreach ($goods as $key => $val) {
                    // 返回库存
                    Db::name('goods')->where('id', $val['goods_id'])->inc('stock', $val['num'])->update();
                }
                Db::name('orders')->where('id', $v['id'])->delete();
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
    }

}